package com.yunxiao.cloud.elasticsearch.controller;

import com.yunxiao.cloud.common.base.BaseResultResponse;
import com.yunxiao.cloud.elasticsearch.entity.UserModel;
import com.yunxiao.cloud.elasticsearch.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * @description: RequestLogController
 * @author: yunxiao
 * @date: 2020/1/14 10:15
 * @version: V1.0
 **/
@Api(value = "测试User-elasticsearch", tags = {"各种封装的测试方法1"})
@RestController
@RequestMapping("esuser")
public class UserController {


    @Autowired
    private UserService userService;

    /**
     * 数据入库 Elastic
     */
    @ApiOperation(value = "数据入库", notes = "数据入库方法")
    @PostMapping("/insert")
    public BaseResultResponse insert() {
        String result = userService.esInsert(10);
        return BaseResultResponse.ok(result);
    }

    /**
     * 查询全部 Elastic
     */
    @PostMapping("/findAll")
    public BaseResultResponse<Iterable<UserModel>> findAll() {
        Iterable<UserModel> requestLogs = userService.esFindAll();
        return BaseResultResponse.ok(requestLogs);
    }

    /**
     * 根据ID修改
     *
     * @param id
     * @return
     */
    @PostMapping("/updateById/{id}")
    public BaseResultResponse updateById(@PathVariable Integer id) {
        UserModel requestLog = new UserModel();
        requestLog.setId(id);
        requestLog.setUserName("updateName");
        String result = userService.esUpdateById(requestLog);
        return BaseResultResponse.ok(result);
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @PostMapping("/selectById/{id}")
    public BaseResultResponse selectById(@PathVariable Integer id) {
        Optional<UserModel> requestLog = userService.esSelectById(id);
        return requestLog.<BaseResultResponse>map(BaseResultResponse::ok).orElseGet(BaseResultResponse::error);
    }

    /**
     * 根据指定条件排序
     */
    @PostMapping("/selectOrder")
    public BaseResultResponse<Iterable<UserModel>> selectOrder() {
        return BaseResultResponse.ok(userService.esFindOrder());
    }

    /**
     * 多条件排序
     */
    @PostMapping("/selectOrders")
    public BaseResultResponse<Iterable<UserModel>> selectOrders() {
        return BaseResultResponse.ok(userService.esFindOrders());
    }

    /**
     * 多条件 + 范围 搜索
     */
    @PostMapping("/search")
    public BaseResultResponse<Iterable<UserModel>> search() {
        return BaseResultResponse.ok(userService.search());
    }
}
